from datetime import datetime

from django.core.cache import cache

from apps.aiauth.models import Userconnection
from apps.aiauth.models import Users
from apps.home.models import Proresult
from utils import restful, md5, tokens, algorithm
from utils.openid import getOpenid
from .models import *
from .serializers import QuestionListSerializers, QuestionTypeListSerializers


# 获取测试题列表
def getQuestionList(request):
    QuestionList = QuestionType.objects.all()
    data = QuestionListSerializers(QuestionList, many=True).data

    return restful.ok(data=data, message='成功')


# 根据id查询对应的题目以及题目对应的选项
def getDetails(request):
    questiontype_id = request.GET.get('questiontype_id')
    Questions = QuestionType.objects.get(questiontype_id=questiontype_id)
    data = QuestionTypeListSerializers(Questions).data

    return restful.ok(data=data, message='成功')


# 获取用户答案，算法分析
def getUserAnswer(request):
    data = request.POST.get('data')
    id = request.POST.get('id')
    userid = request.POST.get('user_id')
    result = algorithm.Algorithm(int(id), data)
    # 获取用户测试数据，若存在，则更新，不存在，则新建
    proResult = Proresult.objects.filter(user=userid, questiontype=id).order_by('-gentime').first()
    user = Users.objects.get(user_id=userid)
    if proResult:
        proResult.resultstrength = result['type']
        proResult.resultweakness = result['describe']
        proResult.resultadvice = result['occupation']
        proResult.countscore = result['count']
        proResult.save()
    else:
        Proresult.objects.create(
            user=user,
            resultstrength=result['type'],
            resultweakness=result['describe'],
            resultadvice=result['occupation'],
            countscore=result['count'],
            questiontype=QuestionType.objects.get(questiontype_id=id),
            gentime=datetime.now()
        )
    return restful.ok(message='成功', data=result)


# 微信登录后，根据openid查找对应账号
def getUserConnection(request):
    jscode = request.GET.get('jscode')
    openid = getOpenid(jscode)
    auth = Userconnection.objects.filter(provideruserid=openid, providerid='mini').first()
    # 将jscode和openid存入redis，方便用户绑定
    cache.set(jscode, openid, 60 * 10)
    if auth:
        user_id = auth.user.user_id
        token_data = {
            'user_id': user_id,
        }
        token = tokens.Token.create_token(data=token_data)
        return restful.result(code=200, message='登录成功！', data={
            'user_id': user_id,
            'token': token
        })
    else:
        # 请求条件不满足，返回304状态码
        return restful.not_modified(message="请先绑定或注册账号！")


# 绑定用户
def bindingUser(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    jscode = request.POST.get('jscode')
    try:
        user = Users.objects.get(studentid=username, password=md5.md5(password))

        # 根据用户id，生成token
        token_data = {
            'user_id': user.user_id,
        }
        token = tokens.Token.create_token(data=token_data)

        # 根据id查询三方表是否存在该用户
        obj = Userconnection.objects.filter(user=user.user_id, providerid='mini').first()
        if obj:
            # 存在，则更新openid
            obj.provideruserid = cache.get(jscode)
            obj.save()
            return restful.ok(message='绑定成功', data={'token': token})
        else:
            # 若不存在，则插入用户与三方登录信息
            Userconnection.objects.create(
                user=user,
                providerid='mini',
                provideruserid=getOpenid(cache.get(jscode)),
                rank=1,
                displayname='',
                profileurl='',
                imageurl='',
                accesstoken='yes',
                secret='',
                refreshtoken='',
                expiretime=''
            )
            return restful.ok(message='绑定成功', data={'token': token, 'user_id': user.user_id})

    except:
        return restful.params_error(message="账号或密码错误，请重新输入！")


# 注册新用户

def registerUser(request):
    username = request.POST.get('username')
    phonenumber = request.POST.get('phonenumber')
    password = request.POST.get('password')
    jscode = request.POST.get('jscode')
    openid = cache.get(jscode)
    try:
        newUser = Users.objects.create(
            role_id=1,
            studentid=username,
            username=username,
            password=password,
            phonenumber=phonenumber,
            gentime=datetime.now(),
            edittime=datetime.now(),
        )
    except:
        # 用户已存在，拒绝访问，返回403
        return restful.forbidden(message='该用户已存在')
    try:
        Userconnection.objects.create(
            user=newUser,
            providerid='mini',
            provideruserid=openid,
            rank=1,
            displayname='',
            profileurl='',
            imageurl='',
            accesstoken='yes',
            secret='',
            refreshtoken='',
            expiretime=None
        )
        # 根据id，生成token
        token_data = {
            'user_id': newUser.user_id,
        }
        token = tokens.Token.create_token(data=token_data)
        return restful.result(
            code=200,
            message='注册成功',
            data={'token': token},
            kwargs={
                'user_id': newUser.user_id
            }
        )
    except:
        # 抛出异常，说明参数错误，返回400
        return restful.params_error(message='注册失败,请重试！')
